#encoding: utf8
""" parse functions

Here must use `from modulename import function` to explicitly import 
correspond parsing function
"""
import re
import json
from BeautifulSoup import BeautifulSoup as BS

def getContentDefault(page):
    """ Default function to parse the content
    """
    return []

# add parse functios Here. TODO
# def parse_function(page):
#    ....

def getPage(page):
    sp = BS(page)
    # get movie type
    film_type = sp.find("ul", {"class":"bread-crumbs"})
    if not film_type or len(film_type) < 2: return None
    try:
        name = film_type.contents[-1].a.text
    except:
        return {}
    if not name: return {}
    try:
        type = film_type.contents[-2].a.text
    except:
        type = u""
    # get movie info
    film_info  = sp.find("div", {"class": "detail-cols fn-clear"})
    info = {}
    img_src_str = ''
    actors = []
    type_detail = []
    region = []
    director = []
    prod_time = []
    prod_plot = ''
    if film_info:
        # img url
        img_src = film_info.findNext("div", {"class": "detail-pic fn-left"}).img
        img_src_str = ''
        if img_src: img_src_str = img_src['src']
        info['img'] = img_src_str
        # actors : list
        info_tag = film_info.find("div", {"class":"info fn-clear"})
        actors = get_info(info_tag, u'主演')
        # type tags
        type_detail = get_info(info_tag, u"类型")
        # region
        region = get_info(info_tag, u"地区")
        # director
        director = get_info(info_tag, u"导演")
        # product year
        prod_time = get_info(info_tag, u"年份")
        # prod_plot
        prod_plot = get_plot(info_tag)
    info = {
            "img": img_src_str,
            "type_detail": type_detail,
            "actors": actors,
            "region": region,
            "director": director,
            "prod_time": prod_time,
            "prod_plot": prod_plot
        }
    return [(name, json.dumps(info))]
        
def get_info(info_tag, info_type):
    """ they are the same construct, include `actors`, `region`, `type` ...
    """
    type_tag = info_tag.find("dt", text=lambda x:x.find(info_type)>=0)
    if not type_tag: return []
    info_container = type_tag.parent.nextSibling
    data = []
    for i in info_container:
        try:
            data.append(i.text)
        except AttributeError:
            pass
    return data
    

def get_plot(info_tag):
    type_tag = info_tag.find("dt", text=lambda x:x.find(u"剧情")>=0)
    if not type_tag: return ''
    info_container = type_tag.parent.nextSibling
    return str(info_container)

